<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <title>Document</title>
    <script src='../vue.global.js'></script>
</head>

<body>
    <div id="watch-example">
        <p>
            Ask a yes/no question:
            <input v-model="question" />
        </p>
        <hr>
        <!-- <p>{{ question }}:{{questionLength}}:{{questionLengthComputed}}</p> -->
        <p>{{ answer }}</p>
        <button @click="getAnswer">getAnswer</button>
    </div>
    <!-- 因为 AJAX 库和通用工具的生态已经相当丰富，Vue 核心代码没有重复 -->
    <!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script> -->
    <!-- <script src="./axios.min.js"></script> -->

    <script>
        const watchExampleVM = Vue.createApp({
            data() {
                return {
                    question: '龙哥是龙吗',
                    answer: '唔母鸡...',
                    questionLength:5
                }
            },

            watch: {
                // 每当 question 发生变化时，该函数将会执行
                // newQuestion为新的question值 oldQuestion为旧值
                question(newQuestion, oldQuestion) {
                    console.log("watch question",newQuestion, oldQuestion);
                    this.questionLength = newQuestion.length

                    if (newQuestion.indexOf('?') > -1) {
                        this.getAnswer()
                    }
                }
            },

            computed:{
                questionLengthComputed(){
                    console.log("questionLengthComputed getter");
                    return this.question.length
                }
            },

            methods: {
                getAnswer() {
                    console.log("getAnswer");
                    this.answer = '让老夫想想...'

                    fetch('https://yesno.wtf/api')
                        .then(response => response.json())
                        .then(data => {
                            this.answer = data.answer
                            console.log("then", this.answer);
                        })
                        .catch(error => {
                            this.answer = 'Error! Could not reach the API. ' + error
                            console.log("catch", this.answer);
                        })
                }
            }
        
        }).mount('#watch-example')
    </script>
</body>

</html>